package com.ttc.mBackupK16.BackupContacts;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ttc.mBackupK16.R;
import com.ttc.mBackupK16.BackupStorage.DropBox;
import com.ttc.mBackupK16.BackupStorage.Email;
import com.ttc.mBackupK16.BackupStorage.FileItemStorage;
import com.ttc.mBackupK16.BackupStorage.SDCard;
import com.ttc.mBackupK16.BackupStorage.StorageObject;
import com.ttc.mBackupK16.BackupStorage.Webservice;

public class RestoreContactsListActivity extends Activity implements
		OnClickListener {

	ContactList myContactList;
	Button btnRestoreContacts, btnCancelContacts;
	CheckBox chBCheckAllContacts;
	ListView lstContacts;
	CustomListAdapter adapter;
	ContactsManager myContactsManager;
	TextView txtContactsNumber, txtContactsNumberChecked;
	StorageObject storageObject;
	ArrayList<FileItemStorage> listFileItem = new ArrayList<FileItemStorage>();
	CharSequence itemFilePath[];
	ProgressDialog progressDialog;
	String resultRestore = "";
	
	final Handler handler = new Handler();
	final Runnable mUpdateResultGetContactsFromFile = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			adapter = new CustomListAdapter(RestoreContactsListActivity.this, R.id.lstContacts, myContactList.getContacts(), txtContactsNumberChecked);
			lstContacts.setAdapter(adapter);
			txtContactsNumber.setText("/" + lstContacts.getCount());
			txtContactsNumberChecked.setText(lstContacts.getCount() + "");
			
			progressDialog.dismiss();
		}
	};
	
	final Runnable mUpdateResultGetFiles = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			showFileBackupListDialog(RestoreContactsListActivity.this, itemFilePath, "Files Backup List", R.drawable.ic_json);
			progressDialog.dismiss();		
		}
	};
	
	final Runnable mUpdateResultRestoreContacts = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub		
			showRestoreContactsResultDialog(resultRestore);
			progressDialog.dismiss();		
		}
	};

	public final static int SDCARD = 0;
	public final static int GMAIL = 1;
	public final static int DROPBOX = 2;
	public final static int MYSERVICE = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts_list);

		Bundle b = this.getIntent().getExtras();
		switch (b.getInt("storage")) {
		case SDCARD:
			storageObject = new SDCard();
			break;
		case GMAIL:
			storageObject = new Email();
			break;
		case DROPBOX:
			storageObject = new DropBox();
			break;
		case MYSERVICE:
			storageObject = new Webservice();
			break;

		default:
			break;
		}

		btnRestoreContacts = (Button) findViewById(R.id.btnBackupContacts);
		btnRestoreContacts.setText("Restore");
		btnRestoreContacts.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_btn_restore, 0, 0, 0);
		
		btnCancelContacts = (Button) findViewById(R.id.btnCancelContacts);
		btnCancelContacts.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_btn_back_home, 0, 0, 0);
		
		chBCheckAllContacts = (CheckBox) findViewById(R.id.chBCheckAllContacts);
		chBCheckAllContacts.setChecked(true);
		
		lstContacts = (ListView) findViewById(R.id.lstContacts);
		txtContactsNumber = (TextView) findViewById(R.id.txtContactsNumber);
		txtContactsNumberChecked = (TextView) findViewById(R.id.txtContactsNumberChecked);

		btnRestoreContacts.setOnClickListener(this);
		btnCancelContacts.setOnClickListener(this);
		chBCheckAllContacts.setOnClickListener(this);

		Thread threadGetBackupFiles = new Thread(){
			public void run() {	
				listFileItem = storageObject.getFilesList("/mBackup/Contacts");
				itemFilePath = new CharSequence[listFileItem.size()];
				for (int i = 0; i < itemFilePath.length; i++) {
					itemFilePath[i] = listFileItem.get(i).getFileName();
				}
				
				handler.post(mUpdateResultGetFiles);
			};
		};
		threadGetBackupFiles.start();
		
		// Create and show ProgressDialog
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Getting backup files....");
		progressDialog.show();
		
		myContactsManager = new ContactsManager();
		myContactsManager.setCr(getContentResolver());
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBackupContacts:
			if (Integer.parseInt(txtContactsNumberChecked.getText().toString()) == 0) {
				Toast.makeText(getBaseContext(),
						"No found any contact checked!", Toast.LENGTH_SHORT)
						.show();
			} else {
				showRestoreContactsDialog();
			}
			break;
		case R.id.btnCancelContacts:
			this.finish();
			break;
		case R.id.chBCheckAllContacts:
			for (int i = 0; i < myContactList.getContacts().size(); ++i) {
				myContactList.getContacts().get(i).setChecked(chBCheckAllContacts.isChecked());
			}
			
			adapter.notifyDataSetChanged();
			
			if (chBCheckAllContacts.isChecked()) {
				txtContactsNumberChecked.setText(lstContacts.getCount() + "");
				adapter.iNumItemChecked = lstContacts.getCount();
			} else {
				txtContactsNumberChecked.setText("0");
				adapter.iNumItemChecked = 0;
			}
			break;
		default:
			break;
		}
	}

	private void showFileBackupListDialog(final Context context, CharSequence[] item, String strTitle, int iIDIcon) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(strTitle);
		
		if (iIDIcon != -1)
			builder.setIcon(iIDIcon);
		
		if (item.length == 0) {
			item = new CharSequence[1];
			item[0] = "No found any backup file!";
		}
		
		builder.setItems(item, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, final int which) {
				// TODO Auto-generated method stub
				if (listFileItem.size() == 0)
					dialog.cancel();
				else {				
					Thread threadGetContactsFromFile = new Thread(){
						public void run() {
							StringBuilder strContactsJson = storageObject.loadFile(listFileItem.get(which).getPath());
							ArrayList<Contact> contactsRestore = convertJsonToContacts(strContactsJson);
							myContactList = new ContactList();
							myContactList.setContacts(contactsRestore);
							
							handler.post(mUpdateResultGetContactsFromFile);
						};
					};
					threadGetContactsFromFile.start();
					
					// Create and show ProgressDialog
					progressDialog = new ProgressDialog(RestoreContactsListActivity.this);
					progressDialog.setMessage("Loading contacts....");
					progressDialog.show();
					
					dialog.dismiss();
				}
			}
		});
		builder.show();
	}
	
	private void showRestoreContactsDialog(){
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Are you sure ?");
		alertDialog.setIcon(R.drawable.ic_warning);
		alertDialog.setMessage("Contacts which you checked, will be restored!");
		alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub		
				Thread threadRestoreContacts = new Thread(){
					public void run() {
						ArrayList<Contact> contacts = new ArrayList<Contact>();
						contacts = myContactList.getContacts();
						for(int i = 0; i< contacts.size(); i++){
							if(contacts.get(i).isChecked()){
								if(myContactsManager.WriteSingleContact(contacts.get(i))){
									resultRestore += "- " + contacts.get(i).getDisplayName() + ": success!" + "\n";
								}
								else{
									resultRestore += "- " + contacts.get(i).getDisplayName() + ": fail!" + "\n";
								}
							}
						}
						
						handler.post(mUpdateResultRestoreContacts);
					};
				};
				threadRestoreContacts.start();
				
				// Create and show ProgressDialog
				progressDialog = new ProgressDialog(RestoreContactsListActivity.this);
				progressDialog.setMessage("Restoring contacts....");
				progressDialog.show();
			}
		});
		alertDialog.setNegativeButton("Cancel", null);
		
		alertDialog.show();
	}
	
	private void showRestoreContactsResultDialog(String result){
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
		alertDialog.setTitle("Result restore contacts");
		alertDialog.setMessage(result);
		alertDialog.setIcon(R.drawable.ic_result);
		alertDialog.setPositiveButton("Ok", null);
		
		alertDialog.show();
	}

	public ArrayList<Contact> convertJsonToContacts(StringBuilder strJson) {
		GsonBuilder gsonb = new GsonBuilder();
		Gson gson = gsonb.create();

		ArrayList<Contact> contacts = new ArrayList<Contact>();
		Contact contactClass = null;

		String tempJson = strJson.toString();
		Log.v("Contacts string", tempJson);
		tempJson = tempJson.replace("{\"addresses\"", "@@");
		Log.v("Contacts string replace", tempJson);
		String itemJson[] = tempJson.split("@@");
		Log.v("So Contacts", itemJson.length + "");

		for (int i = 1; i < itemJson.length; i++) {
			try {
				contactClass = null;
				String strContactJson = "{\"addresses\"" + itemJson[i];
				Log.v("strcontactJson", strContactJson);
				contactClass = gson.fromJson(strContactJson, Contact.class);
				contacts.add(contactClass);
			} catch (Exception e) {
				Log.e("error conver json to contact", e.getMessage());
			}
		}

		return contacts;
	}
}
